#include "client.h"
#include<sys/socket.h>
#include<unistd.h>
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
void uploadFile(int netfd, train_t *train)
{
	char filename[4096] = { 0 };
	strncpy(filename, train->_data, train->_length);
	int access_ret = access(filename, F_OK);
	if (access_ret == -1) {
		return access_ret;
	}
	train->_length = strlen(filename);
	memcpy(train->_data, filename, train->_length);
	int send_filename_ret = send(
		netfd, &train,
		sizeof(train->_length) + sizeof(train->taskType) + train->_length,
		MSG_NOSIGNAL);
	ERROR_CHECK(send_filename_ret, -1, "send fliename");

	int fd = open(filename, O_RDWR);
	ERROR_CHECK(fd, -1, "open file");

	while (1) {
		ssize_t read_ret = read(fd, train->_data, sizeof(train->_data));
		ERROR_CHECK(read_ret, -1, "read train.buff");

		train->_length = read_ret;
		if (read_ret != 1000 && read_ret != -1) {
			printf("read_ret=%lu\n", read_ret);
		}
		int send_filedata_ret =
			send(netfd, train,sizeof(train->_length) + sizeof(train->taskType),train->_length);
		ERROR_CHECK(send_filedata_ret, -1, "send filedata");
		if (read_ret == 0) {
			break;
		}
	}
	return 0;
}

void downloadFile(int netfd, train_t *train)
{
	int filename_length_ret =
		recv(netfd, &train->_length, sizeof(train->_length), MSG_WAITALL);
	ERROR_CHECK(filename_length_ret, -1, "recv filename train.length");

	int filename_buff_ret =
		recv(netfd, &train->_data, sizeof(train->_data), MSG_WAITALL);
	ERROR_CHECK(filename_buff_ret, -1, "recv filename train.buff");

	char filename[4096] = { 0 };
	memcpy(filename, train->_data, train->_length);
	int fd = open(filename, O_RDWR | O_CREAT | O_TRUNC, 0666);
	ERROR_CHECK(fd, -1, "open file");

	while (1) {
		int filedata_length_ret =
			recv(netfd, &train->_data, sizeof(train->_length),
			     MSG_WAITALL);
		ERROR_CHECK(filedata_length_ret, -1,
			    "recv filedata train.length");

		if (train->_length != 1000) {
			printf("train.length=%d\n", train->_length);
		}
		if (train->_length == 0) {
			break;
		}
		int filedata_buff_ret =
			recv(netfd, &train->_data, train->_length, MSG_WAITALL);
		ERROR_CHECK(filedata_buff_ret, -1, "recv filedata_buff_ret");

		int write_ret = write(fd, train->_data, train->_length);
		ERROR_CHECK(write_ret, -1, "write");
	}
	return 0;
}					